/*
    8. Write a program in C to delete a specific line from a file. 
    Assume that the content of the file test.txt is :                                                                       
    test line 1                                                                                                   
    test line 2                                                                                                   
    test line 3                                                                                                   
    test line 4                                                                                                   
    Test Data :
    Input the file name to be opened : test.txt
    Input the line you want to remove : 2
    Expected Output :

    The content of the file test.txt is :                                                                       
    test line 1                                                                                                   
    test line 3                                                                                                   
    test line 4
*/

#include <stdio.h>

#define MAX_STR 1024

int main(void)
{
    FILE *fp1, *fp2;
    char filename[64];
    char tmpfile[] = "tmp.txt";
    char str[MAX_STR];
    int line, curline = 0;
    int ret;
    printf("Input the file name to be opened : ");
    scanf("%s", filename);
    fflush(stdin);
    printf("Input the line you want to remove : ");
    scanf("%d", &line);
    fp1 = fopen(filename, "r");
    fp2 = fopen(tmpfile, "w+");
    while(fgets(str, MAX_STR, fp1) != NULL){
        curline++;
        if(curline != line){
            fputs(str, fp2);
        }
    }
    fclose(fp1);
    fclose(fp2);
    ret = remove(filename);
    if(ret == -1){
        printf("remove error at line :  %d", __LINE__);
        return -1;
    }
    ret = rename(tmpfile, filename);
    if(ret == -1){
        printf("rename error at line :  %d", __LINE__);
        return -1;
    }
    fp1 = fopen(filename, "r");
    printf("The content of the file %s is : \n", filename);
    while(fgets(str, MAX_STR, fp1)){
        printf("%s", str);
    }
    fclose(fp1);

    return 0;
}